package handler

import (
	"gitee.com/sansaniot/ssiot-core/httpmvc"
	jwt "gitee.com/sansaniot/ssiot-core/httpmvc/jwtauth"
	"gitee.com/sansaniot/ssiot-core/httpmvc/jwtauth/user"
	"gitee.com/sansaniot/ssiot-core/serrors"
	"github.com/gin-gonic/gin"
	"net/http"
	"ssadmin/common/constant"
	"ssadmin/internal/admin/models"
	"time"
)

// Authenticator login时认证，查库获取用户信息，设置缓存
func Authenticator(c *gin.Context) (interface{}, error) {
	return AuthenticatorFromAccount(c)
}

// PayloadFunc Authenticator返回的profile
func PayloadFunc(data interface{}) jwt.MapClaims {
	if data != nil {
		userInfo := data.(models.User)
		return jwt.MapClaims{
			constant.CacheKeyUserName: userInfo.Username,
		}
	}
	return jwt.MapClaims{}
}

// LoginLogToDB Write log to database
func LoginLogToDB(c *gin.Context, msg string, userInfo models.User) {
	if len(userInfo.UserId) > 0 {
		//更新用户登录时间
		userInfo.LastLoginTime = time.Now()
		db, _ := httpmvc.GetOrm(c)
		db.Model(&userInfo).Updates(&userInfo)
	}
}

// Logout 登出
func Logout(c *gin.Context) {
	userId, _ := user.Get(c, constant.CacheKeyUserId).(string)
	LoginLogToDB(c, "退出成功", models.User{UserId: userId})
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "退出成功",
		"success": true,
	})
}

func Refresh(c *gin.Context, code int, token string, expire time.Time) {
	result := make(map[string]interface{})
	result["token"] = token
	result["expire"] = expire.Format(time.RFC3339)

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"result":  result,
		"success": true,
		"message": "token刷新成功",
	})
}

func LoginResponse(c *gin.Context, code int, token string, expire time.Time) {
	if msg, ok := c.Get("loginError"); ok {
		c.JSON(http.StatusOK, gin.H{
			"code":    serrors.WrongPassword,
			"success": false,
			"message": msg,
		})
	} else {
		result := make(map[string]interface{})
		result[constant.CacheKeyToken] = token
		result[constant.CacheKeyUserInfo], _ = c.Get(constant.CacheKeyUserInfo)
		result["expire"] = expire.Format(time.RFC3339)
		c.JSON(http.StatusOK, gin.H{
			"code":    serrors.OK,
			"success": len(token) != 0,
			"result":  result,
			"message": serrors.Msg(serrors.OK),
		})
	}
}

func Unauthorized(c *gin.Context, code int, message string) {
	c.JSON(http.StatusUnauthorized, gin.H{
		"code":    http.StatusUnauthorized,
		"success": false,
		"message": message,
	})
}

func CheckLogin(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "ok",
		"success": true,
	})
}
